package com.lagou.rpc.consumer.handler;

import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * 客户端处理类（基于线程处理方式）
 * 1.发送消息
 * 2.接收消息
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<RpcResponse> implements Callable {
    ChannelHandlerContext context;
    //发送的消息
//    String requestMsg;
    RpcRequest requestMsg;
    //服务端响应的消息
//    String responseMsg;
    RpcResponse rpcResponseMsg;

    public void setRequestMsg(RpcRequest requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道连接就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context = ctx;
    }

    /**
     * 通道读取就绪事件
     * @param channelHandlerContext
     * @param responseMsg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse responseMsg) throws Exception {
        rpcResponseMsg = responseMsg;
        notify();
    }


    /**
     * 发送消息到服务端
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        //消息发送
        context.writeAndFlush(requestMsg);
        //线程等待
        wait();
        return rpcResponseMsg;
    }
}
